import axios, { AxiosInstance, AxiosResponse, AxiosRequestHeaders } from 'axios';
import { showLoading, hideLoading } from './Loading';
import storage from './storage';
import envConfig from '@/config';
import { message } from '@/utils/AntdGlobal';

console.log(import.meta.env, '编译时环境变量');
console.log(envConfig, '运行时环境变量');

// 创建 axios 实例
const instance: AxiosInstance = axios.create({
  // baseURL: import.meta.env.VITE_BASE_API,
  baseURL: envConfig.baseApi,
  timeout: 5000,
  timeoutErrorMessage: '请求超时',
});

// 请求拦截器
instance.interceptors.request.use(
  config => {
    // 确保 headers 存在
    config.headers = config.headers || {};
    if (config.showLoading) showLoading({tip: 'Loading'})
    // 可以在这里添加 token 等认证信息
    const token = storage.get('token');
    if (token) {
      (config.headers as AxiosRequestHeaders).Authorization = `Bearer ${token}`;
    }
    // config.headers.icode = 'B815F86524423DB0'
    // 判断mock是否开启
    // if(import.meta.env.VITE_USE_MOCK === 'true') {
    //   config.baseURL = import.meta.env.VITE_MOCK_API
    // }

    if(envConfig.mock) {
      config.baseURL = envConfig.mockApi
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// 响应拦截器
instance.interceptors.response.use(
  (response: AxiosResponse) => {
    hideLoading()
    console.log(response.data)
    if (response.data.code != 0) {
      if (response.config.showError === false) {
        return Promise.resolve(response.data)
      } else {
        message.error(response.data.msg)
        return Promise.reject(response.data)
      }
    }
    return response.data;
  },
  error => {
    hideLoading()
    // 统一处理错误
    if (error) {
      switch (error.status) {
        case 401:
          // 处理未授权
          break;
        case 403:
          // 处理禁止访问
          break;
        case 404:
          // 处理资源未找到
          break;
        case 500:
          // 处理服务器内部错误
          break;
        default:
          console.error('请求失败:', error.data);
      }
    }
    return Promise.reject(error);
  }
);

// 局部loading和局部报错封装
interface IConfig {
  showLoading?: boolean
  showError?: boolean
}
export default {
  get<T>(url: string, params?: object, options: IConfig = { showLoading: true, showError: true }): Promise<T> {
    return instance.get(url, { params, ...options });
  },
  post<T>(url: string, data?: object, options: IConfig = { showLoading: true, showError: true }): Promise<T> {
    return instance.post(url, data, options);
  },
  put<T>(url: string, data?: object): Promise<T> {
    return instance.put(url, data);
  },
  delete<T>(url: string, params?: object): Promise<T> {
    return instance.delete(url, { params });
  }
};
// 封装请求方法
// export default {
//   get<T>(url: string, params?: object): Promise<T> {
//     return instance.get<T>(url, { params }).then(response => response.data);
//   },
//   post<T>(url: string, data?: object): Promise<T> {
//     return instance.post<T>(url, data).then(response => response.data);
//   },
//   put<T>(url: string, data?: object): Promise<T> {
//     return instance.put<T>(url, data).then(response => response.data);
//   },
//   delete<T>(url: string, params?: object): Promise<T> {
//     return instance.delete<T>(url, { params }).then(response => response.data);
//   }
// };
